package TCP_test2;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class MyThread implements Runnable {

    private ServerSocket serverSocket;
    public MyThread(ServerSocket serverSocket){
        this.serverSocket=serverSocket;
    }
    @Override
    public void run() {
        try {
            //等待客户端连接
            Socket socket = null;
            socket = serverSocket.accept();
            //获取输入流
            BufferedInputStream bis = null;
            bis = new BufferedInputStream(socket.getInputStream());
            //防止文件名重复
            String name= UUID.randomUUID().toString().replace("-", "");
            //获取输出流
            BufferedOutputStream bos = null;
            bos = new BufferedOutputStream(new FileOutputStream("文件名"));
            byte[]bytes=new byte[2024];
            int len;
            while(true){
                    if (!((len=bis.read(bytes))!=-1)) break;
                    bos.write(bytes,0,len);
            }
            //回写数据
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("上传成功");
            bw.newLine();
            bw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        finally {
            try {
                serverSocket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
